package com.ys.malini.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 显示随机验证码的Servlet
 * 
 * @author zhoup
 * @date Apr 21, 2009
 * 
 */
public class RandomImageServlet extends HttpServlet {
	
	private static final long serialVersionUID = -8584041841501416165L;
    private static int WIDTH = 60;   
    private static int HEIGHT = 20;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();   
		  
        // 设置浏览器不要缓存此图片   
        response.setHeader("Pragma", "No-cache");   
        response.setHeader("Cache-Control", "no-cache");   
        response.setDateHeader("Expires", 0);   
        response.setContentType("image/jpeg");   
  
        // 创建内存图象并获得其图形上下文   
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);   
        Graphics g = image.getGraphics();   
  
        // 产生随机的认证码并画图   
        char[] rands = this.generateCheckCode();   
        this.drawBackground(g);   
        this.drawRands(g, rands);   
  
        // 结束图像的绘制过程，完成图像   
        g.dispose();   
  
        // 将当前验证码存入到Session中   
        session.setAttribute("validateCode", new String(rands));
        session.setAttribute("validateCodeTime", new Date());
  
        // 将图像输出到客户端   
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());   
        encoder.encode(image);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// doGet(request,response);
	}
	
	/**  
     * 产生随机数。  
     * @return  
     */  
    private char[] generateCheckCode()   
    {   
        // 定义验证码的字符表   
        //String chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    	String chars = "01234567890123456789012345678901234567890123456789";
        char[] rands = new char[4];   
        for (int i = 0; i < 4; i++)   
        {   
            int rand = (int) (Math.random() * 28); 
            if(rand>=50){
            	rand=9;
            }
            rands[i] = chars.charAt(rand);   
        }   
        return rands;   
    }   
  
    /**  
     * 画随机数。  
     * @param g  
     * @param rands  
     */  
    private void drawRands(Graphics g, char[] rands)   
    {   
        g.setColor(Color.BLACK);   
        g.setFont(new Font(null, Font.PLAIN | Font.BOLD, 18));   
        // 在不同的高度上输出验证码的每个字符   
        g.drawString("" + rands[0], 1, 17);   
        g.drawString("" + rands[1], 16, 15);   
        g.drawString("" + rands[2], 31, 18);   
        g.drawString("" + rands[3], 46, 16);   
        //System.out.println(rands);   
    }   
  
    /**  
     * 画图片背景。  
     * @param g  
     */  
    private void drawBackground(Graphics g)   
    {   
        g.setColor(new Color(0xDCDCDC));   
        g.fillRect(0, 0, WIDTH, HEIGHT);   
        // 随机产生120个干扰点   
        for (int i = 0; i < 120; i++)   
        {   
            int x = (int) (Math.random() * WIDTH);   
            int y = (int) (Math.random() * HEIGHT);   
            int red = (int) (Math.random() * 255);   
            int green = (int) (Math.random() * 255);   
            int blue = (int) (Math.random() * 255);   
            g.setColor(new Color(red, green, blue));   
            g.drawOval(x, y, 1, 0);   
        }   
    }
	
}
